package com.byzk.p2p.admin.borrow.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.borrow.dao.BorrowDao;
import com.byzk.p2p.admin.borrow.dao.BorrowGroupUserDao;
import com.byzk.p2p.admin.borrow.dao.TenderDao;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.BorrowApply;
import com.byzk.p2p.admin.borrow.dto.BorrowApplyOff;
import com.byzk.p2p.admin.borrow.dto.BorrowGroup;
import com.byzk.p2p.admin.borrow.dto.BorrowGroupUser;
import com.byzk.p2p.admin.borrow.dto.UserTender;
import com.byzk.p2p.admin.borrow.util.BorrowStatus;
import com.byzk.p2p.admin.borrow.vo.BorrowApplyVo;
import com.byzk.p2p.admin.borrow.vo.BorrowGroupUserVo;
import com.byzk.p2p.admin.borrow.vo.BorrowRepayExportVo;
import com.byzk.p2p.admin.borrow.vo.BorrowTempVo;
import com.byzk.p2p.admin.borrow.vo.BorrowVo;
import com.byzk.p2p.admin.money.dao.FundRecordDao;
import com.byzk.p2p.admin.money.dto.FundRecord;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.vo.SumMoneyVo;
import com.byzk.p2p.admin.score.dao.ScoreRecordDao;
import com.byzk.p2p.admin.score.dto.ScoreRecord;
import com.byzk.p2p.admin.system.dao.SystemDao;
import com.byzk.p2p.admin.system.dto.SystemConfig;
import com.byzk.p2p.admin.user.dao.UserAccountDao;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.front.vo.CalculatorVo;

@Service
public class BorrowService {
	@Autowired
	private BorrowDao borrowDao;
	@Autowired
	private BorrowGroupUserDao borrowGroupUserDao;
	@Autowired
	private TenderDao tenderDao;
	@Autowired
	private UserAccountDao accountDao;
	@Autowired	
	private SystemDao systemDao;
	@Autowired
	private ScoreRecordDao scoreDao;
	@Autowired
	private FundRecordDao recordDao;
	
	/**
	 * 用户申请审批列表
	 * @param status 提现状态
	 * @return
	 */
	
	public PageInfo<BorrowApplyVo> listBorrowApply(BorrowApplyVo vo){
		int count=borrowDao.countByStatus(vo);
		List<BorrowApplyVo> appLyList=borrowDao.listBorrowApply(vo);
		PageInfo<BorrowApplyVo> page=new PageInfo<BorrowApplyVo>(count,vo.getIndex() ,vo.getLimit());
		page.setPageList(appLyList);
		return page;
	}
	
	public BorrowApplyVo getBorrowApplyVo(Integer id){
		return borrowDao.getBorrowApplyVoById(id);
	}

	public BorrowApply getBorrowApply(Integer id){
		return borrowDao.getBorrowApplyById(id);
	}
	public Integer saveOrUpdateBorrowApply(BorrowApply borrowApply){
		if(borrowApply.getId()==null){
			return borrowDao.insert(borrowApply);
		}else{
			return borrowDao.update(borrowApply);
		}
	}
	
	public Integer saveOrUpdateBorrow(Borrow borrow){
		if(borrow.getId()==null){
			return borrowDao.insertBorrow(borrow);
		}else{
			return borrowDao.updateBorrow(borrow);
		}
	}
	
	public Integer saveOrUpdateBorrowApplyOff(BorrowApplyOff off){
		if(off.getId()==null){
			return borrowDao.insertBorrowApplyOff(off);
		}else{
			return borrowDao.updateBorrowApplyOff(off);
		}
	}	

	public PageInfo<Borrow> listBorrowExceptNew(BorrowVo borrowVo){
		int count=borrowDao.countBorrow(borrowVo);
		List<Borrow> borrowList=borrowDao.listBorrowExceptNew(borrowVo);
		PageInfo<Borrow> page=new PageInfo<Borrow>(count, borrowVo.getIndex(), borrowVo.getLimit());
		page.setPageList(borrowList);
		return page;
	}
	
	public PageInfo<BorrowVo> listBorrow(BorrowVo borrowVo){
		int count=borrowDao.countBorrowAll(borrowVo);
		List<BorrowVo> borrowList=borrowDao.listBorrow(borrowVo);
		SumMoneyVo sumMoneyVo = borrowDao.sumBorrow(borrowVo);
		PageInfo<BorrowVo> page=new PageInfo<BorrowVo>(count, borrowVo.getIndex(), borrowVo.getLimit());
		if(sumMoneyVo == null){
			page.setSum(0.0);
			page.setSumBlance(0.0);
			page.setSumFee(0.0);
		}else{
			page.setSum(sumMoneyVo.getAmount());
			page.setSumBlance(sumMoneyVo.getFund());
			page.setSumFee(sumMoneyVo.getInterest());
		}
		page.setPageList(borrowList);
		return page;
	}
	/**
	 * 查询所有新手标
	 * @param borrowVo
	 * @return
	 */
	public PageInfo<BorrowVo> listNewBorrow(BorrowVo borrowVo){
		int count=borrowDao.countNewBorrow(borrowVo);
		List<BorrowVo> borrowList=borrowDao.listNewBorrow(borrowVo);
		SumMoneyVo sumMoneyVo = borrowDao.sumNewBorrow(borrowVo);
		PageInfo<BorrowVo> page=new PageInfo<BorrowVo>(count, borrowVo.getIndex(), borrowVo.getLimit());
		if(sumMoneyVo == null){
			page.setSum(0.0);
			page.setSumBlance(0.0);
			page.setSumFee(0.0);
		}else{
			page.setSum(sumMoneyVo.getAmount());
			page.setSumBlance(sumMoneyVo.getFund());
			page.setSumFee(sumMoneyVo.getInterest());
		}
		page.setPageList(borrowList);
		return page;
	}
	
	public Borrow detailBorrow(Integer id){
		return borrowDao.getBorrowById(id);
	}
	
	public BorrowVo detailBorrowVo(Integer id){
		BorrowVo borrow = borrowDao.getBorrowVoById(id);
		CalculatorVo vo = new CalculatorVo();
		vo.setMoney(100.0);
		vo.setYearRate(borrow.getPercent());
		vo.setInterestMethod(borrow.getPaymentMode());
		vo.setPeriod(borrow.getDeadline());
		vo.setPeriodUnit(borrow.getDateUtil());
		CalculatorVo cal = BaseUtil.calculator(vo);
		Double tenderInterest = 0.0;
		if(cal.getTotleInterest() != null) {
			tenderInterest = BaseUtil.StringToDoubletoFixed2(Double.parseDouble(cal.getTotleInterest()));
		}
		borrow.setTenderInterest(tenderInterest);
		return borrow;
	}
	
	public List<BorrowTempVo> getBorrowVoByUid(Integer uid){
		return borrowDao.getBorrowVoByUid(uid);
	}
	
	/**
	 * 获取标的情况
	 * @param borrow
	 * @return
	 */
	public PageInfo<BorrowTempVo> getBorrow(BorrowTempVo borrow){
		int count=borrowDao.getBorrowCount(borrow);
		List<BorrowTempVo> borrowList=borrowDao.getBorrow(borrow);
		PageInfo<BorrowTempVo> page=new PageInfo<BorrowTempVo>(count, borrow.getIndex(), borrow.getLimit());
		page.setPageList(borrowList);
		return page;
	}
	
	/**
	 * 所有的借款标组
	 * @return
	 */
	public List<BorrowGroup> listBorrowGroup(){
		return borrowGroupUserDao.listBorrowGroup();
	}
	
	/**
	 * 获取借款标组
	 * @return
	 */
	public List<BorrowGroup> listBorrowGroupByCondition(BorrowGroup borrowGroup){
		return borrowGroupUserDao.listBorrowGroupByCondition(borrowGroup);
	}
	
	/**
	 * 根据借款标组id获取组用户
	 * @param borrowGroupId 借款标组id
	 * @return
	 */
	public List<BorrowGroupUserVo> getUserByBorrowGroupId(Integer borrowGroupId){
		return borrowGroupUserDao.getUsersByBorrowGroupId(borrowGroupId);
	}
	
	/**
	 * 根据借款标组用户
	 * @return
	 */
	public PageInfo<BorrowGroupUserVo> getBorrowGroupUsers(BorrowGroupUserVo borrowGroupUserVo){
		int count=borrowGroupUserDao.getGroupUsersCount(borrowGroupUserVo);
		List<BorrowGroupUserVo> borrowGroupUserVos = borrowGroupUserDao.getGroupUsers(borrowGroupUserVo);
		PageInfo<BorrowGroupUserVo> page=new PageInfo<BorrowGroupUserVo>(count, borrowGroupUserVo.getIndex(), borrowGroupUserVo.getLimit());
		page.setPageList(borrowGroupUserVos);
		return page;
	}
	
	/**
	 * 获取所有特殊标组的用户
	 * @return
	 */
	public List<BorrowGroupUserVo> getBorrowGroupUsers(){
		return borrowGroupUserDao.getBorrowGroupUsers();
	}
	
	/**
	 * 删除特殊标组用户
	 * @param borrowGroupId 特殊组id
	 * @return
	 */
	public Integer deleteBorrowGroupUsers(Integer borrowGroupId){
		return borrowGroupUserDao.delete(borrowGroupId);
	}
	
	/**
	 * 保存特殊标组的用户
	 * @param borrowGroupUsers
	 * @return
	 */
	public Integer save(List<BorrowGroupUser> borrowGroupUsers){
		return borrowGroupUserDao.insert(borrowGroupUsers);
	}
	
	public List<Borrow> lastBorrowList(int total){
		return borrowDao.lastBorrowList(total);
	}
	
	public List<Borrow> listLastNewBorrow(){
		return borrowDao.listLastNewBorrow();
	}

	public Borrow getBorrowById(Integer borrowId) {
		return borrowDao.getBorrowById(borrowId);
	}
	
	public int cancelBorrow(Integer borrowId){
		List<UserTender> tenderList=tenderDao.getByBorrowId(borrowId);
		if(tenderList.size()>0){
				
/*			//投资金额转化积分比率
			int temp=100;
			List<SystemConfig> configList=systemDao.listSystemConfig();
			if(configList !=null && configList.size()>0){
				temp=configList.get(0).getAmount();
			}*/
			
			List<UserAccount> accountList=new ArrayList<UserAccount>();
			List<ScoreRecord> scoreList=new ArrayList<ScoreRecord>();
			List<FundRecord> fundList=new ArrayList<FundRecord>();
			for (UserTender tender : tenderList) {
				UserAccount account=accountDao.getByUserId(tender.getUserId());
				account.setFreezen(account.getFreezen()-tender.getAmount());
				account.setBalance(account.getBalance()+tender.getAmount());
/*				int score=(int) (tender.getAmount()/temp);
				account.setScore(account.getScore()-score);
				accountList.add(account);*/
				
				FundRecord fund=new FundRecord();
				fund.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
				fund.setCreateTime(new Date());
				fund.setRemark("流标资金解冻");
				fund.setType(FundRecordType.Type.UNFREEZEN.index);
				fund.setUserId(tender.getUserId());
				fund.setIncome(tender.getAmount());
				fund.setExpend(0.0);
				fund.setTerminal("PC");
				fundList.add(fund);
				
				//扣除积分
				ScoreRecord scoreRecord = new ScoreRecord();
				scoreRecord.setUserId(tender.getUserId());
				scoreRecord.setOptType("out");
				/*scoreRecord.setAmount(score);*/
				scoreRecord.setWay("积分撤回(流标)");
				scoreRecord.setCreateTime(new Date());
				scoreRecord.setTerminal("PC");
				scoreList.add(scoreRecord);
			}
			accountDao.batchUpdate(accountList);
			scoreDao.batchInsert(scoreList);
			recordDao.batchInsert(fundList);
		}
		Borrow borrow=borrowDao.getBorrowById(borrowId);
		borrow.setStatus(BorrowStatus.EXPIRE);
		borrowDao.updateBorrow(borrow);
		
		return 1;
	}
	
	
	public Borrow lastBorrow(){
		return borrowDao.lastBorrow();
	}
	
	public List<BorrowTempVo> exportList(BorrowRepayExportVo vo){
		return borrowDao.listByExportVo(vo);
	}
	
	/**
	 * 获取借款标的还款情况
	 * @param borrow
	 * @return
	 */
	public PageInfo<BorrowTempVo> getBorrowRepay(BorrowTempVo borrow){
		int count=borrowDao.getBorrowRepayCount(borrow);
		List<BorrowTempVo> borrowList=borrowDao.getBorrowRepay(borrow);
		SumMoneyVo sumMoneyVo = borrowDao.sumCompleteBorrow(borrow);
		PageInfo<BorrowTempVo> page=new PageInfo<BorrowTempVo>(count, borrow.getIndex(), borrow.getLimit());
		if(sumMoneyVo == null){
			page.setSum(0.0);
			page.setSumComplete(0.0);
			page.setSumFee(0.0);
		}else{
			page.setSum(sumMoneyVo.getAmount());
			page.setSumComplete(sumMoneyVo.getFund());
			page.setSumFee(sumMoneyVo.getInterest());
		}
		page.setPageList(borrowList);
		return page;
	}
	
	//以完成的还款
	public BorrowVo paymentBorrowVo(Integer id){
		return borrowDao.getborrowPaymentById(id);
	}
	//还款中
	public BorrowVo payBorrowVo(Integer id){
		return borrowDao.getborrowPaymentById(id);
	}
	
	public Integer countAll(){
		return borrowDao.countAll();
	}
	
	public Borrow getByCode(String code){
		return borrowDao.getByCode(code);
	}
	
	public Borrow platinaBorrow(){
		return borrowDao.platinaBorrow();
	}
	
	public Borrow newBorrow(){
		return borrowDao.newBorrow();
	}
	
	/**
	 * 首页标的数据
	 * @param limit 记录的条数
	 * @return
	 */
	public List<BorrowVo> FrontborrowList(int limit) {
		BorrowVo borrowVo = new BorrowVo();
		borrowVo.setIndex(1);
		borrowVo.setLimit(limit);
		List<BorrowVo> listBorrow = borrowDao.borrowList(borrowVo);
		/** 计算预约倒计时 **/
		for(BorrowVo borrow : listBorrow) {
			if(borrow.getTimingShow() != null){
				int second = (int) ((borrow.getTimingShow().getTime()-new Date().getTime())/1000L);
				if(second > 0 && second < (60*60*2)) {//两小时以内
					borrow.setCountDown(DateUtils.formatSecond(second));
				}
			}
		}
		return listBorrow;
	}
	
	public PageInfo<BorrowVo> borrowList(BorrowVo borrowVo){
		int count=borrowDao.countBorrow(borrowVo);
		List<BorrowVo> borrowList=borrowDao.borrowList(borrowVo);
		/** 计算预约倒计时 **/
		for(BorrowVo borrow : borrowList) {
			if(borrow.getTimingShow() != null){
				int second = (int) ((borrow.getTimingShow().getTime()-new Date().getTime())/1000L);
				if(second > 0 && second < (60*60*2)) {//两小时以内
					borrow.setCountDown(DateUtils.formatSecond(second));
				}
			}
		}
		SumMoneyVo sumMoneyVo = borrowDao.sumBorrow(borrowVo);
		PageInfo<BorrowVo> page=new PageInfo<BorrowVo>(count, borrowVo.getIndex(), borrowVo.getLimit());
		if(sumMoneyVo == null){
			page.setSum(0.0);
			page.setSumBlance(0.0);
			page.setSumFee(0.0);
		}else{
			page.setSum(sumMoneyVo.getAmount());
			page.setSumBlance(sumMoneyVo.getFund());
			page.setSumFee(sumMoneyVo.getInterest());
		}
		page.setPageList(borrowList);
		return page;
	}
	
	public List<Borrow> lastBorrowListVo(int productId,int total){
		return borrowDao.lastBorrowListVo(productId,total);
	}
	
	public Borrow selectByPmerBillNo(String pMerBillNo){
		return borrowDao.selectByPmerBillNo(pMerBillNo);
	}
	
	public List<BorrowApply> selectBorrowApplyByUserId(int userId){
		return borrowDao.selectBorrowApplyByUserId(userId);
	}
	
	public SumMoneyVo statisticByUserId(Integer id){
		return borrowDao.statisticByUserId(id);
	}
	
	public SumMoneyVo paymentNumber(Integer id){
		return borrowDao.paymentNumber(id);
	}
	/**
	 * 
	* <p>Description: 还款中的标</p>
	* <p>Company:xbd </p>
	* @author:lilei
	* @date:2016年9月27日下午5:14:06
	 */
	public List<BorrowVo> payBorrowList(){
		return borrowDao.getborrowPaymentList();
	}
}
